import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_key.dart';
import 'package:app/src/http/bean/worksdo/equipment_management_bean.dart';
import 'package:app/src/manager/audit_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/model/user_model.dart';
import 'package:app/src/http/model/ywx_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/toast/toast.dart';
import 'package:app/src/utils/image_path_utils.dart';
import '../../../http/model/todo_review_model.dart';
import '../../../manager/user_manager.dart';
import 'user/user.dart';
import 'dart:convert' as convert;
import 'home/home.dart';

///主页面
class MainRoute extends StatefulWidget {
  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<MainRoute> with SingleTickerProviderStateMixin {
  TabController? _tabController;
  _MainPresenter presenter = _MainPresenter();

  ///当前选中菜单下标
  var currentIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController =
        TabController(length: 2, initialIndex: currentIndex, vsync: this)
          ..addListener(() {
            //tab标签滑动改变时，会回调。fixme tab标签选中改变时回调。没有改动不会回调。
            //print('TabController滑动监听：\t');
            setState(() {
              currentIndex = _tabController?.index ?? 0;
              if (currentIndex == 1) {
                //用户
                currentIndex = 3;
              }
            });
          });
    presenter?.mainState = this;

    ///获取用户信息;fixme 打包之后，这里调用，好像不会跳转。不知道为什么没有起作用。所以这里就不调用了。home.dart里调用一次就够了。
    ///UserPresenter?.getpersoninfo(context, (value){},isAutoLogin: true,isAuto: true,isEnableLoad: false);

    ///fixme 获取待审核数据
    presenter?.getTodoReview(context);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //fixme 焦点管理清除
    FocusNodeManager.clear();
  }

  DateTime? _lastPressedAt; //上次点击时间
  @override
  Widget build(BuildContext context) {
    var material = Material(
      child: Scaffold(
        bottomNavigationBar: bottomNavigationBar(context),
        body: Builder(
          builder: (context) {
            if (presenter.ywxDatas != null) {
              return tabBar(context);
            }
            return FutureBuilder<List<YwxLimit>?>(
                future: presenter.mockNetworkData(context),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  // print(
                  //     "=======================================================请求状态:${snapshot.connectionState}\t${snapshot.connectionState == ConnectionState.done}"
                  //         "hasError:${snapshot.hasError}\tdata:${snapshot.data}");
                  // 请求已结束
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError || snapshot.data == null) {
                      // 请求失败，显示错误
                      // var center= Center(child: Text("Error: ${snapshot.error}"),);
                      //网络连接异常,点击重试
                      return Center(
                        child: Column(
                          children: [
                            MaterialButton(
                                child: Text(
                                    AppStrings.of(context).setServerAddress2),
                                onPressed: () {
                                  AppRouteHelper.goSerVerAddressRoute(context);
                                }),
                            SizedBox(height: 16),
                            AppUi.materialButton(
                                AppStrings.of(context).refresh2, onPressed: () {
                              setState(() {});
                            })
                          ],
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                        ),
                      );
                      // return Center(
                      //   child: MaterialButton(
                      //     child: Text(AppStrings.of(context).refresh),
                      //     onPressed: () {
                      //       setState(() {});
                      //     },
                      //   ),
                      // );
                    } else {
                      presenter.ywxDatas = snapshot.data;
                      s_YwxDatas = presenter.ywxDatas;
                      // 请求成功，显示数据
                      return tabBar(context);
                    }
                  } else {
                    // 请求未结束，显示loading
                    return Center(
                      child: CircularProgressIndicator(
                        strokeWidth: 1,
                      ),
                    );
                  }
                });
          },
        ),
      ),
    );
    // return WillPopScope(
    //   child: material,
    //   onWillPop: () async {
    //     if (_lastPressedAt == null ||
    //         DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) {
    //       //两次点击间隔超过1秒则重新计时
    //       _lastPressedAt = DateTime.now();
    //       MyToast.showInfo(
    //           LibStrings.of(context).pressToExit, context); //再按一次退出
    //       return false; //fixme 当前路由（页面）不出栈（不关闭）
    //     } else {
    //       // if (PlatformUtils.isAndroid()) {
    //       //   AppRouteHelper.goHome(context); //直接退回到桌面。
    //       //   return false;
    //       // }
    //     }
    //     return true; //fixme 关闭当前页面。
    //   },
    // );
    return AppUi.popScope(context, material);
  }

  ///tab菜单
  Widget tabBar(BuildContext context) {
    return TabBarView(
      physics: NeverScrollableScrollPhysics(),
      //NeverScrollableScrollPhysics()不具备滑动效果。
      controller: _tabController,
      //fixme TabBarView 和 TabBar共用一个controller；且tab数量必须一致。不然报错
      children: [
        Center(
          child: HomePage(),
        ),
        Center(
          child: UserPage(),
        ),
      ],
    );
  }

  ///当前选中图片颜色
  Color getSelectColorWithImage(int index) {
    if (currentIndex == index) {
      return ColorUtils.parseColor("#042ADB");
    } else {
      return ColorUtils.parseColor("#211816");
    }
  }

  ///当前选中字体颜色
  Color getSelectColorWithText(int index) {
    if (currentIndex == index) {
      return ColorUtils.parseColor("#042ADB");
    } else {
      return Colors.black;
    }
  }

//底部菜单
  Widget bottomNavigationBar(BuildContext context) {
    // print(
    //     "底部菜单选中下标======================================================$currentIndex");
    return BottomNavigationBar(
      onTap: (index) {
        UserPresenter?.getpersoninfo(
          context,
          (value) {
            if (AppRouteHelper.isValidation(context, isAuto: true)) {
              //fixme 验证用户通过
              // print("底部菜单选中下标1：$index");
              //点击事件，回调index为当前下标。从0开始。
              ///=============================================
              if (index == 1) {
                //扫描
                AppRouteHelper.goScanRoute(context, (value) {
                  if (value != null) {
                    presenter?.toScanResult(context, value);
                  }
                });
              } else if (index == 2) {
                //打卡
                AppRouteHelper.goClockinRoute(context);
              } else {
                setState(() {
                  if (index == 0) {
                    //首页
                    currentIndex = 0;
                    _tabController?.animateTo(0);
                  } else if (index == 3) {
                    //用户
                    currentIndex = 3;
                    _tabController?.animateTo(1);
                  }
                  // print("底部菜单选中下标2：$index");
                });
              }

              ///=============================================
            }
          },
          isAuto: false,
          isAutoLogin: true,
          isEnableLoad: true,
        );
      },
      elevation: 10,
      currentIndex: currentIndex,
      selectedItemColor: ColorUtils.parseColor("#042ADB"),
      unselectedItemColor: Colors.black,
      selectedLabelStyle: TextStyle(color: ColorUtils.parseColor("#042ADB")),
      unselectedLabelStyle: TextStyle(color: Colors.black),
      showSelectedLabels: true,
      //fixme 选中时显示labels文本
      showUnselectedLabels: true,
      //fixme 未选中时，显示labels文本; 最好手动设置，items少于或等于3是默认显示的；大于或等于4个时，默认是不显示的。
      items: [
        //首页
        BottomNavigationBarItem(
          icon: Hero(
            tag: AppUi.hero_tag_launch,
            child: Image.asset(
              ImagePathUtils.getPathWithImage("ic_home1.png"),
              width: 44,
              color: getSelectColorWithImage(0),
            ),
          ), //icon 一般为图标
          label: AppStrings.of(context).home_page,
          // title: Text(
          //   AppStrings.of(context).home_page,
          //   style: TextStyle(color: getSelectColorWithText(0)),
          // ),
        ),
        //扫一扫
        BottomNavigationBarItem(
          icon: Image.asset(
            ImagePathUtils.getPathWithImage("ic_menu_scan1.png"),
            width: 24,
            color: getSelectColorWithImage(1),
          ), //icon 一般为图标
          label: AppStrings.of(context).scan,
          // title: Text(
          //   AppStrings.of(context).scan,
          //   style: TextStyle(color: getSelectColorWithText(1)),
          // ),
        ),
        //考勤
        BottomNavigationBarItem(
          icon: Image.asset(
            ImagePathUtils.getPathWithImageMenu("01.png"),
            width: 24,
            color: getSelectColorWithImage(2),
          ), //icon 一般为图标
          label: AppStrings.of(context).ClockIn2,
          // title: Text(
          //   AppStrings.of(context).scan,
          //   style: TextStyle(color: getSelectColorWithText(1)),
          // ),
        ),
        //用户
        BottomNavigationBarItem(
          icon: Image.asset(
            ImagePathUtils.getPathWithImage("ic_user1.png"),
            width: 24,
            color: getSelectColorWithImage(3),
          ), //icon 一般为图标
          label: AppStrings.of(context).user,
          // title: Text(
          //   AppStrings.of(context).user,
          //   style: TextStyle(color: getSelectColorWithText(2)),
          // ),
        )
      ], //fixme BottomNavigationBarItem 个数不能少于两个，不然报错。
    );
  }
}

List<YwxLimit>? s_YwxDatas = null; //fixme 静态权限，方便全局调用；

class _MainPresenter {
  _MainState? mainState;
  List<YwxLimit>? ywxDatas = null;

  ///获取菜单权限
  Future<List<YwxLimit>?> mockNetworkData(BuildContext context) async {
    return YwxModel.getYwxLimits(context, false);
  }

  ///解析扫码结果
  void toScanResult(BuildContext context, String value) {
    if (value!.contains(AppKey.getTokenBwg())) {
      Map<String, dynamic> map = convert.jsonDecode(value);
      var code = map[AppKey.getTokenBwg()];
      if (code != null) {
        setscancode(context, code);
      }
    } else {
      //扫描结果
      AppRouteHelper.goScanResultRoute(context, value);
    }
  }

  ///扫码登录
  void setscancode(
    BuildContext context,
    String code,
  ) {
    UserModel.setscancode(context, true, code, '1', (value) {
      if (value.isSuccessForCode()) {
        //扫码登录成功
        Toast.showSuccess(
            AppStrings.of(context).loginSuccessfulForScan, context);
      } else {
        AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
      }
    });
  }

  //获取待审核数据
  void getTodoReview(BuildContext context) {
    //30
    TimerUtils.periodic(15, () {
      // print("周期执行了1");
      try {
        if (mainState?.mounted ?? false) {
          // print("周期执行了2");
          if (!AppDialog.isShowDialog() &&
              !AuditManager.getAuditManager().getDetailsWithAuto()) {
            // print("周期执行了3");
            TodoReviewModel.getTdogetlist(context, false,
                    PageNo: "0", PageSize: "1", isEquipmentInfo: true)
                ?.then((value) {
              // print("周期执行了4");
              if (value != null) {
                try {
                  // print("周期执行了5");
                  if (!AppDialog.isShowDialog()) {
                    // print("周期执行了6");
                    if (mainState?.mounted ?? false) {
                      // print("周期执行了7");
                      if (UserManager.getUserInfo() != null) {
                        EquipmentInfo? TicketCenter; //工单中心；
                        if (StringUtils.isNotEmpty(value.TicketCenter)) {
                          TicketCenter = value.TicketCenter![0];
                        }
                        EquipmentInfo? Myworkorder; //我的工单；
                        if (StringUtils.isNotEmpty(value.Myworkorder)) {
                          Myworkorder = value.Myworkorder![0];
                        }
                        // TicketCenter = EquipmentInfo()
                        //   ..AddTime = "2023-12-06 12:12:41";
                        // Myworkorder = EquipmentInfo()
                        //   ..DispatchingTime = "2023-12-06 12:12:40"; //测试数据
                        var isShowEquipment = showNewDialogWithEquipment(
                            context,
                            TicketCenter,
                            Myworkorder); //fixme 优先显示工单信息。
                        if (!isShowEquipment) {
                          // print("周期执行了8\t${TicketCenter?.AddTime}\t${Myworkorder?.DispatchingTime}");
                          //TodoReviewModel.newNotice?.showNewDialog(context);
                          if ((TodoReviewModel.newNotice?.isNew() ?? false)) {
                            // if ((TodoReviewModel.newNotice?.isNew() ?? false) ||
                            //     true) {
                            //fixme true为测试。
                            // print("周期执行了9");
                            TodoReviewModel.newNotice?.showNewDialog(context);
                          }
                        }
                      }
                    }
                  }
                } catch (e) {
                  print("待审核数据周期刷新异常2：$e");
                }
              }
            });
          }
        }
      } catch (e) {
        print("待审核数据周期刷新异常：$e");
      }
      return true;
    });
  }
}
